<?php
namespace App\Http\Controllers\Api\FlyGo;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis as Redis;
use App\Models\Goods\GoodsSale;
use App\Models\Customer\Customer;
use App\Models\Pay\SysPaytype;
use App\Models\Activity\AlipayCustomerCardMap;
use App\Models\Card\CardCoupon;
use App\Models\Card\CardCouponMall;

class CartController extends Controller
{

    const bigShoppingBag = '0.30';  //大购物袋价格

    const smallShoppingBag = '0.20';    //小购物袋价格

    private $bill_array;

    private $pcustID;

    private $auto_code;

    private $shop_id;

    /**
     * 普通商品加入购物车
     * @param Request $request
     */
    public function add( Request $request )
    {
        $productId = $request->input('productId');
        if (empty($productId)) {
            return response()->json(['code' => 10001, 'message' => '缺少productId参数']);
        }

        $number = $request->input('number');
        if (empty($number) || !is_numeric($number)) {
            return response()->json(['code' => 10002, 'message' => '缺少number参数']);
        }

        $userId = $request->input('userId');
        if (empty($userId)) {
            return response()->json(['code' => 10003, 'message' => '缺少userId参数']);
        }

        $mallID = $request->input('mallID');
        if (empty($mallID)) {
            $mallID = 0;
        }

        //购物车key
        $cart_name = 'shop_cart';

        $auto_code = $cart_name . '_' . $userId;

        //获取购物车信息
        $bill_array = self::getCartInfo($auto_code);

        if (!isset($bill_array['goods']['general'][$productId])) {

            $goods_array = GoodsSale::getCache($productId, $mallID);
            if (!$goods_array) {
                return response()->json(['code' => 10004, 'message' => '商品信息没有找到']);
            }

            if ($goods_array['salePrice'] <= 0) {
                return response()->json(['code' => 10005, 'message' => '商品价格错误，请重新扫码']);
            }
            $goods_array['goods_amount'] = $number;
            $cart_goods_array = self::createCartGoodsStructure($goods_array);

        } else {
            $cart_goods_array = $bill_array['goods']['general'][$productId];
            $cart_goods_array['goods_amount'] += $number;
        }

        $bill_array['goods']['general'][$productId] = $cart_goods_array;
        if ($cart_goods_array['goods_amount'] <= 0) {
            unset($bill_array['goods']['general'][$productId]);
        }

        //初始化购物袋数组
        if (!isset($bill_array['goods']['shopping_bag'])) {
            $bill_array['goods']['shopping_bag'] = [];
        }

        //保存购物车信息
        $bill_array['bill_config_id'] = 1;

        $bill_array['goods']['change_time'] = time();

        Redis::setex($auto_code, 360000, json_encode($bill_array));

        return response()->json(['code' => 200, 'message' => 'ok']);

    }

    /**
     * 删除购物车商品
     * @param Request $request
     */
    public function del( Request $request )
    {
        $productId = $request->input('productId');
        if (empty($productId)) {
            return response()->json(['code' => 10001, 'message' => '缺少productId参数']);
        }

        $userId = $request->input('userId');
        if (empty($userId)) {
            return response()->json(['code' => 10002, 'message' => '缺少userId参数']);
        }

        //购物车key
        $cart_name = 'shop_cart';

        $auto_code = $cart_name . '_' . $userId;

        //获取购物车信息
        $bill_array = self::getCartInfo($auto_code);

        //商品已在购物车里
        if (isset($bill_array['goods']['general'][$postID])) {
            unset($bill_array['goods']['general'][$postID]);
        }

        //更新购物车信息
        $bill_array['change_time'] = time();

        Redis::setex($auto_code, 360000, json_encode($bill_array));

        return response()->json(['code' => 200, 'message' => 'ok']);
    }

    /**
     * 购物袋加入购物车
     * @param Request $request
     */
    public function addShoppingBag( Request $request )
    {
        $bagName = $request->input('bagName');
        if (empty($bagName)) {
            return response()->json(['code' => 10001, 'message' => '缺少bagName参数']);
        }

        $number = $request->input('number');
        if (empty($number)) {
            return response()->json(['code' => 10002, 'message' => '缺少number参数']);
        }

        $userId = $request->input('userId');
        if (empty($userId)) {
            return response()->json(['code' => 10003, 'message' => '缺少userId参数']);
        }

        if ($bagName == 'bigShoppingBag') {
            $goodsName = '大购物袋';
            $salePrice = self::bigShoppingBag;
        } else {
            $goodsName = '小购物袋';
            $salePrice = self::smallShoppingBag;
        }

        //购物车key
        $cart_name = 'shop_cart';

        $auto_code = $cart_name . '_' . $userId;

        //获取购物车信息
        $bill_array = self::getCartInfo($auto_code);
        if (!isset($bill_array['goods']['shopping_bag'][$bagName])) {
            $cart_goods_array = array(
                'productId'    => $bagName,
                'goodsName'    => $goodsName,
                'marketPrice'  => $salePrice,
                'salePrice'    => $salePrice,
                'price'        => $salePrice,
                'goods_amount' => $number,
                'addPoints'    => 0,
                'salePoints'   => 0

            );
        } else {
            $cart_goods_array = $bill_array['goods']['shopping_bag'][$bagName];
            $cart_goods_array['goods_amount'] += $number;
        }

        $bill_array['goods']['shopping_bag'][$bagName] = $cart_goods_array;

        if ($cart_goods_array['goods_amount'] <= 0) {
            unset($bill_array['goods']['shopping_bag'][$bagName]);
        }

        $bill_array['goods']['change_time'] = time();

        Redis::setex($auto_code, 360000, json_encode($bill_array));

        return response()->json(['code' => 200, 'message' => 'ok']);
    }

    /**
     * 删除购物袋
     * @param Request $request
     */
    public function delShoppingBag( Request $request )
    {
        $bagName = $request->input('bagName');
        if (empty($bagName)) {
            return response()->json(['code' => 10001, 'message' => '缺少bagName参数']);
        }

        $userId = $request->input('userId');
        if (empty($userId)) {
            return response()->json(['code' => 10003, 'message' => '缺少userId参数']);
        }

        //购物车key
        $cart_name = 'shop_cart';

        $auto_code = $cart_name . '_' . $userId;

        $bill_array = self::getCartInfo($auto_code);

        if (isset($bill_array['goods']['shopping_bag'][$bagCode])) {
            unset($bill_array['goods']['shopping_bag'][$bagCode]);
        }

        //更新购物车信息
        $bill_array['change_time'] = time();

        Redis::setex($auto_code, 360000, json_encode($bill_array));

        return response()->json(['code' => 200, 'message' => 'ok']);
    }

    /**
     * 购物车加载
     * @param Request $request
     */
    public function index( Request $request )
    {
        $userId = $request->input('userId');
        if (empty($userId)) {
            return response()->json(['code' => 10001, 'message' => '缺少userId参数']);
        }

        $mallID = $request->input('mallID');
        if (empty($mallID)) {
            $mallID = 0;
        }

        $cart_name = 'shop_cart';   //购物车key
        $auto_code = $cart_name . '_' . $userId;
        $this->bill_array = self::getCartInfo($auto_code);
        $this->shop_id = $mallID;
        $this->pcustID = $userId;
        $this->auto_code = $auto_code;

        //初始化优惠券使用
        if (isset($this->bill_array['use_coupon'])) {
            unset($this->bill_array['use_coupon']);
        }

        //初始化主商品信息
        $this->bill_array['master'] = [
            'bill_totalMoney' => 0,
            'bill_totalPaid' => 0,
            'bill_totalPoints' => 0,
            'bill_pointsPrice' => 0,
            'bill_subtract_money' => 0,
            'bill_coupon_money' => 0,
            'bill_payable' => 0,
            'bill_total_amount' => 0,
            'billType' => 1,
            'remark' => null,
            'payment_method_id' => null
        ];

        $cust_master = Customer::find($this->pcustID);
        if (!$cust_master) {
            return response()->json(['code' => 10002, 'message' => '会员信息未找到']);
        }

        $c = [];

        //获取支付方式（微信支付）
        $pay_data = SysPaytype::find(50);
        if (!$pay_data) {
            return response()->json(['code' => 10003, 'message' => '支付方式未找到']);
        }
        $pay_data = $pay_data->toArray();
        $c['pay'][] = [
            'pay_type'      => $pay_data['type'],
            'pay_type_name' => '在线支付',
            'payTypeID'     => $pay_data['payTypeID'],
            'payTypeName'   => $pay_data['payTypeName'],
            'select'        => 1
        ];

        $this->bill_array['master']['pay_type'] = $pay_data['type'];
        $this->bill_array['master']['payTypeID'] = $pay_data['payTypeID'];
        $this->bill_array['master']['payTypeName'] = $pay_data['payTypeName'];

        //默认使用最大折扣优惠券
        $default_coupon = [];

        $goods_array = self::goodsColligate($this->bill_array);
        if (!$goods_array) {
            return response()->json(['code' => 10004, 'message' => '购物车未加入商品']);
        }

        $c['coupon'] = [];
        $cardCoupon = self::getCardCoupon($goods_array, $this->pcustID, $this->shop_id);
        if (isset($cardCoupon['coupon']) && !empty($cardCoupon['coupon'])) {
            foreach($cardCoupon['coupon'] as $coupon) {
                $return_coupon = [
                    'code' => $coupon['code'],
                    'couponType' => $coupon['cardType'],
                    'typeName' => '代金券',
                    'amount' => $coupon['amount'],
                    'discount' => $coupon['discount'],
                    'title' => $coupon['amount'],
                    'content' => '满'.$coupon['code_limit_amount'].'元使用',
                    'date' => $coupon['start_date'].' - '.$coupon['end_date'],
                    'select' => 0,
                    'canUse' => $coupon['canUse']
                ];
                if ($coupon['cardType'] == 2) {
                    $return_coupon['typeName'] = '折扣券';
                    $return_coupon['title'] = $coupon['discount']*10 . '折';
                }
                $c['coupon'][$coupon['code']] = $return_coupon;

                if ((!$default_coupon || $coupon['amount'] > $default_coupon['amount']) && $coupon['canUse'] == 1) {
                    $default_coupon = [
                        'code' => $coupon['code'],
                        'amount' => $coupon['amount'],
                        'discount' => $coupon['discount'],
                        'couponID' => $coupon['couponID'],
                        'couponName' => $coupon['couponName'],
                        'cardType' => $coupon['cardType'],
                        'code_limit_amount' => $coupon['code_limit_amount']
                    ];
                }
            }
        }
        if ($default_coupon) {
            $this->bill_array['use_coupon'] = $default_coupon;
            $c['coupon'][$default_coupon['code']]['select'] = 1;
        }
        $c['coupon'] = array_values($c['coupon']);
        $c['coupon_usCount'] = $cardCoupon['usCount'];
        $c['coupon_unUsCount'] = $cardCoupon['unUsCount'];

        //添加购物袋到数据结构中
        $c['bigShoppingBagPrice'] = self::bigShoppingBag;
        $c['smallShoppingBagPrice'] = self::smallShoppingBag;

        return response()->json($this->set($c));
    }

    /**
     * 使用优惠券
     * @param Request $request
     */
    public function use_coupon( Request $request )
    {
        $userId = $request->input('userId');
        if (empty($userId)) {
            return response()->json(['code' => 10001, 'message' => '缺少userId参数']);
        }

        $code = $request->input('code');
        if (empty($code)) {
            return response()->json(['code' => 10002, 'message' => '缺少code参数']);
        }

        $mallID = $request->input('mallID');
        if (empty($mallID)) {
            $mallID = 0;
        }

        //购物车key
        $cart_name = 'shop_cart';

        $auto_code = $cart_name . '_' . $userId;

        $this->bill_array = self::getCartInfo($auto_code);
        $this->shop_id = $mallID;
        $this->pcustID = $userId;
        $this->auto_code = $auto_code;

        if ($this->bill_array['master']['bill_payable'] <= 0) {
            return response()->json(['code' => 10003, 'message' => '订单已付款,不需要再使用优惠券抵扣']);
        }

        $goods_array = self::goodsColligate($this->bill_array);
        if (!$goods_array) {
            return response()->json(['code' => 10004, 'message' => '购物车未添加商品']);
        }

        //检查优惠券是否可用
        $result_array = self::checkCoupon($code, $this->pcustID, $goods_array, $this->shop_id);
        if ($result_array['code'] != 200) {
            return response()->json(['code' => $result_array['code'], 'message' => $result_array['message']]);
        }

        $this->bill_array['use_coupon'] = [
            'code' => $result_array['data']['code'],
            'amount' => $result_array['data']['amount'],
            'discount' => $result_array['data']['discount'],
            'couponID' => $result_array['data']['couponID'],
            'couponName' => $result_array['data']['couponName'],
            'cardType' => $result_array['data']['cardType'],
            'code_limit_amount' => $result_array['data']['code_limit_amount']
        ];

        $coupon_array = [
            'code' => self::toString($result_array['data']['code']),
            'type' => self::toInt($result_array['data']['cardType']),
            'type_name' => '代金券',
            'remark' => '满'.$result_array['data']['code_limit_amount'].'元使用',
            'date_time' => $result_array['data']['start_date'].' - '.$result_array['data']['end_date']
        ];

        if ($result_array['data']['cardType'] == 2) {
            $coupon_array['type_name'] = '折扣券';
        }

        return response()->json($this->set(null, $coupon_array));
    }

    /**
     * 取消使用优惠券
     * @param Request $request
     */
    public function cancel_coupon( Request $request )
    {
        $userId = $request->input('userId');
        if (empty($userId)) {
            return response()->json(['code' => 10001, 'message' => '缺少userId参数']);
        }

        $code = $request->input('code');
        if (empty($code)) {
            return response()->json(['code' => 10002, 'message' => '缺少code参数']);
        }

        $mallID = $request->input('mallID');
        if (empty($mallID)) {
            $mallID = 0;
        }

        //购物车key
        $cart_name = 'shop_cart';

        $auto_code = $cart_name . '_' . $userId;

        $this->bill_array = self::getCartInfo($auto_code);
        $this->auto_code = $auto_code;

        if (isset($this->bill_array['use_coupon']) && !empty($this->bill_array['use_coupon'])) {
            unset($this->bill_array['use_coupon']);
        }

        return response()->json($this->set());
    }

    /**
     * 获取redis值
     * @param $key
     * @return null/string/array
     */
    public static function getRedisValue($key)
    {
        $tmp = json_decode(Redis::get($key), true);
        if (!$tmp) {
            return null;
        }

        $sc_timestamp = $tmp['SC_TIMESTAMP'];
        $sc_timeout = $tmp['SC_TIMEOUT'];
        if (($sc_timeout == -1 || $sc_timeout == 0) || ($sc_timeout > 0 && time() - $sc_timestamp <= $sc_timeout)) {
            return $tmp['SC_VALUE'];
        } else {
            return null;
        }
    }

    /**
     * 初始化购物车数据结构
     * @return array
     */
    public static function createCartStructure()
    {

        $bill_array = [

            'bill_no' => null,

            'bill_status' => 0,

            //订单主表
            'master' => [
                'bill_totalMoney' => 0,
                'bill_totalPaid' => 0,
                'bill_totalPoints' => 0,
                'bill_pointsPrice' => 0,
                'bill_subtract_money' => 0,
                'bill_coupon_money' => 0,
                'bill_payable' => 0,
                'bill_total_amount' => 0,
                'billType' => 1,
                'remark' => null,
                'payment_method_id' => null
            ],

            //订单配置
            'bill_config_id' => 1,

            'change_time' => null,

            'message' => null,

            //订单商品
            'goods' => [
                'general' => [],
                'shopping_bag' => []
            ],

            //赠送优惠券
            'gift_coupon' => [],

            //订单促销
            'bill_promotion' => []
        ];

        return $bill_array;

    }

    /**
     * 初始化购物车商品结构
     * @param $goods_array
     * @return array
     */
    public static function createCartGoodsStructure($goods_array, $type=1) {

        $goods_array['addPoints'] = 0;
        $goods_array['goods_groupID'] = 0;
        $goods_array['price'] = $goods_array['salePrice'];
        if (strstr($goods_array['spec'], '-默认')) {
            $goods_array['spec'] = '';
        }

        return array (
            'mainPostID' => $goods_array['mainPostID'],
            'goodsID' => $goods_array['goodsID'],
            'postID' => $goods_array['postID'],
            'goodsName' => $goods_array['goodsName'],
            'spec' => $goods_array['spec'],
            'goods_amount' => $goods_array['goods_amount'],
            'salePrice' => $goods_array['salePrice'],
            'price' => $goods_array['price'],
            'recordPrice' => $goods_array['recordPrice'],
            'addPoints' => $goods_array['addPoints'],
            'salePoints' => $goods_array['salePoints'],
            'goodsWeight' => $goods_array['goodsWeight'],
            'goodsRate'=>$goods_array['goodsRate'],
            'goods_from' => $type,
            'goods_groupID' => $goods_array['goods_groupID'],
            'goods_status' => 1,
            'is_buy' => 1,
            'img_link' => getenv('WEB_HOST') . $goods_array['goodsMainPic'],
            'link' => '',
            'wap_link' => '',
            'product_code' => $goods_array['product_code'],
            'product_spec' => $goods_array['product_spec'],
            'marketPrice' => $goods_array['marketPrice'],
            'supplier_id' => $goods_array['supplier_id'],
            'promotion' => null,
            'promotion_id' => 0,
            'goodsType' => isset($goods_array['goodsType'])?$goods_array['goodsType']:1,
            'virtual_id' => isset($goods_array['virtual_id'])?$goods_array['virtual_id']:0,
            'virtual_name' =>  isset($goods_array['virtual_name'])?$goods_array['virtual_name']:'',
            'virtual_type' =>  isset($goods_array['virtual_type'])?$goods_array['virtual_type']:1,
            'time_slot_id' =>  isset($goods_array['time_slot_id'])?$goods_array['time_slot_id']:0
        );
    }

    /**
     * 获取购物车信息
     * @param $auto_code
     * @return array
     */
    public static function getCartInfo($auto_code)
    {

        $bill_array = Redis::get($auto_code);
        if (!$bill_array) {
            $bill_array = self::createCartStructure();
        } else {
            $bill_array = json_decode($bill_array, true);
        }

        return $bill_array;
    }

    /**
     * 获取符合使用优惠券的商品
     * @param $bill_array
     */
    public static function goodsColligate($bill_array)
    {

        $bill_goods = isset($bill_array['goods']) ? $bill_array['goods'] : '';

        $goods_array = [];

        if (isset($bill_goods['general']) && !empty($bill_goods['general'])) {

            foreach ($bill_goods['general'] as $list) {

                if (isset($list['is_buy']) && $list['is_buy'] == 0) {
                    continue;
                }

                $goods_array[] = array(
                    'postID'      => $list['postID'],
                    'price'       => $list['price'],
                    'goodsAmount' => $list['goods_amount']
                );
            }
        }

        return $goods_array;
    }

    /**
     * 获取优惠券列表
     * @param $goods_array
     * @param $pcustID
     * @param int $shop_id
     */
    public static function getCardCoupon($goods_array, $pcustID, $shop_id = 0)
    {
        $return_data = array(
            'usCount' => 0,
            'unUsCount' => 0,
            'coupon' => []
        );

        //优惠券列表
        $coupon_list = AlipayCustomerCardMap::where([
            ['pcustID', '=', $pcustID],
            ['code_status', '=', 1],
            ['code_start_time', '<=', Carbon::now()],
            ['code_end_time', '>=', Carbon::now()]
        ])->get();

        if ($coupon_list) {

            foreach ($coupon_list as $key => $list) {

                $unset = 0;

                $coupon_master = CardCoupon::find($list->activity_id);

                if (!$coupon_master) {
                    $unset = 1;
                }

                if (isset($coupon_master->support_condition) && $coupon_master->support_condition == 2) {
                    $unset = 1;
                }

                if (isset($coupon_master->mall_support_type) && $coupon_master->mall_support_type == 2) {
                    $card_coupon_mall = CardCouponMall::where([
                        'card_id' => $coupon_master->card_id,
                        'relation_id' => $shop_id,
                        'relation_type' => 1
                    ])->count();
                    if ($card_coupon_mall == 0) {
                        $unset = 1;
                    }
                }

                if (isset($list->code_use_type) && !in_array($list->code_use_type, [1, 2])) {
                    $unset = 1;
                }

                if ($unset == 1) {
                    unset($coupon_list[$key]);
                }
            }

            foreach ($coupon_list as $list) {

                $result_array = self::checkCoupon($list->barcode, $pcustID, $goods_array, $shop_id);

                $code = array(
                    'code' => $list->barcode,
                    'cardType' => $list->code_type==6 ? 1 : 2,
                    'amount' => isset($result_array['data']['amount']) ? $result_array['data']['amount'] : $list->code_amount,
                    'discount' => round($list->code_discount/100, 2),
                    'couponID' => $list->activity_id,
                    'couponName' => $list->activity_name,
                    'start_date' => date('Y-m-d', strtotime($list->code_start_time)),
                    'end_date' => date('Y-m-d', strtotime($list->code_end_time)),
                    'code_limit_amount' => $list->code_limit_amount,
                    'canUse' => 0
                );

                if ($result_array['code'] == 200) {
                    $return_data['usCount']++;
                    $code['canUse'] = 1;
                } else {
                    $return_data['unUsCount']++;
                }

                $return_data['coupon'][$code['code']] = $code;

            }
        }

        return $return_data;
    }

    /**
     * 查询优惠券是否可用
     * @param $code
     * @param $pcustID
     * @param $goods_array
     * @param int $shop_id
     */
    public static function checkCoupon($code, $pcustID, $goods_array, $shop_id = 0)
    {

        $coupon_code_array = AlipayCustomerCardMap::find($code);

        if (!$coupon_code_array) {

            //卡券编号信息没有找到，检查是否是万能码
            $coupon_master = Cardcoupon::where([
                'wncode' => $code,
                'provide_type' => 3,
                'useFlg' => 1
            ])->first();

            if (!$coupon_master) {
                return ['code' => 404, 'message' => '卡券不存在'];
            }

            //检查卡券是否已过期
            if ($coupon_master->use_end_time < Carbon::now()) {
                return ['code' => 404, 'message' => '卡券已过期'];
            }

            $coupon_code_array = [
                'code_start_time' => $coupon_master->use_start_time,
                'code_end_time' => $coupon_master->use_end_time
            ];

        } else {

            $coupon_code_array = $coupon_code_array->toArray();

            //检查是否是当前会员的卡券
            if (!empty($coupon_code_array['pcustID']) && $coupon_code_array['pcustID'] != $pcustID) {
                return ['code' => 404, 'message' => '卡券不存在'];
            }

            //检查卡券是否已过期
            if ($coupon_code_array['code_end_time'] < Carbon::now()) {
                return ['code' => 404, 'message' => '卡券已过期'];
            }

            //检查卡券是否已使用
            if ( $coupon_code_array['code_status'] == 2 ) {
                return ['code' => 404, 'message' => '卡券已使用'];
            }

            $coupon_master = CardCoupon::find($coupon_code_array['activity_id']);
            if (!$coupon_master) {
                return ['code'  => 404, 'message' => '卡券不存在'];
            }

            if ($coupon_master->useFlg != 1) {
                return ['code' => 404, 'message' => '卡券已禁用'];
            }
        }

        if ($coupon_master->support_condition == 2) {
            return ['code' => 400, 'message' => '此卡券只支持线下使用'];
        }

        if ($coupon_master->mall_support_type == 2) {
            $card_coupon_mall = CardCouponMall::where([
                'card_id' => $coupon_master->card_id,
                'relation_id' => $shop_id,
                'relation_type' => 1
            ])->count();
            if ($card_coupon_mall == 0) {
                $unset = 1;
            }
        }

        //符合条件商品总金额、总数量
        $total_money = 0;

        $goods_amount = 0;

        //筛选商品
        $select_goods = json_decode($coupon_master->selectorID_json, true);
        foreach ($goods_array as $goods) {
            if ($select_goods['selector_type'] == 2) {
                if ($select_goods['selector_relation'] && !in_array($goods['postID'], $select_goods['select_goods'])){
                    continue;
                }

                if (!$select_goods['selector_relation'] && in_array($goods['postID'], $select_goods['select_goods'])) {
                    continue;
                }
            }
            $total_money += $goods['price'] * $goods['goodsAmount'];
            $goods_amount += $goods['goodsAmount'];
        }

        //没有符合条件的商品
        if ($goods_amount == 0) {
            return ['code'=>404, 'message'=>'没有符合优惠券条件的商品'];
        }

        //商品金额不满足优惠券使用限额
        if ($total_money < $coupon_master->limit_money) {
            return ['code'=>404, 'message'=>'商品金额不满足优惠券使用限额'];
        }

        //如果是折扣券，转换成减免的金额
        if ($coupon_master->card_type == 2 ) {
            $coupon_master->amount = $total_money * (1-$coupon_master->discount);
        }

        //编号卡券没有绑定会员
        if ($coupon_master->provide_type == 1 && empty($coupon_code_array['pcustID'])) {
            AlipayCustomerCardMap::find($code)->update(['pcustID' => $pcustID]);
        }

        $return_array = array(
            'code'              => $code,
            'cardType'          => $coupon_master->card_type,
            'amount'            => $coupon_master->amount,
            'discount'          => $coupon_master->discount,
            'couponID'          => $coupon_master->card_id,
            'couponName'        => $coupon_master->card_name,
            'code_start_time'   => $coupon_code_array['code_start_time'],
            'code_end_time'     => $coupon_code_array['code_end_time'],
            'start_date'        => date('Y-m-d', strtotime($coupon_code_array['code_start_time']) ),
            'end_date'          => date('Y-m-d', strtotime($coupon_code_array['code_end_time']) ),
            'code_limit_amount' => $coupon_master->limit_money
        );

        return ['code' => 200, 'message' => 'ok', 'data' => $return_array];
    }

    /**
     * 设置购物车输出
     * @param null $c
     * @param null $data
     */
    public function set($c=null, $data=null)
    {
        $checkoutData = [];

        $goodsData = [];

        $return_array = self::checkout($this->bill_array, $this->pcustID, $this->shop_id);

        if ($return_array['code'] == 200) {

            $this->bill_array = $return_array['data'][0];

            $cData = $return_array['data'][1];

            //结算金额信息
            $checkoutData = [
                'bill_total_fee' => self::toString($cData['bill_totalMoney'], '0'),
                'total_fee' => self::toString($cData['bill_totalPaid'], '0'),
                'user_fee' => self::toString($cData['bill_payable'], '0'),
                'total_num' => self::toInt($cData['bill_total_amount']),
                'coupon_fee' => self::toString($cData['bill_coupon_money'], '0'),
                'total_points' => self::toString($cData['bill_totalPoints'], '0'),
                'points_price' => self::toString($cData['bill_pointsPrice'], '0'),
            ];

            //普通商品
            if (isset($cData['goods']['general']) && !empty($cData['goods']['general'])) {
                foreach ($cData['goods']['general'] as $key => $goods) {
                    $totalPrice = sprintf('%.2f', $goods['price'] * $goods['goods_amount']);
                    $goodsData['general'][] = [
                        'productId'     => self::toInt($goods['postID']),
                        'productName'   => self::toString($goods['goodsName']),
                        'img'           => self::toString($goods['img_link']),
                        'spec'          => self::toString($goods['spec']),
                        'price'         => self::toString($goods['price'], '0'),
                        'number'        => self::toInt($goods['goods_amount']),
                        'totalPrice'    => self::toString($totalPrice, '0')
                    ];
                }
            } else {
                $goodsData['general'] = [];
            }

            //购物袋
            if (isset($cData['goods']['shopping_bag']) && !empty($cData['goods']['shopping_bag'])) {
                foreach ($cData['goods']['shopping_bag'] as $key => $goods) {
                    $totalPrice = sprintf('%.2f', $goods['price'] * $goods['goods_amount']);
                    $goodsData['shopping_bag'][] = [
                        'productId'   => self::toString($goods['productId']),
                        'productName' => self::toString($goods['goodsName']),
                        'price'       => self::toString($goods['price'], '0'),
                        'number'      => self::toInt($goods['goods_amount']),
                        'totalPrice'  => self::toString($totalPrice, '0')
                    ];
                }
            } else {
                $goodsData['shopping_bag'] = [];
            }
        }

        if (!is_null($c)) {
            $c['goods'] = $goodsData;
            $c['checkoutData'] = $checkoutData;
        } else {
            $data['checkoutData'] = $checkoutData;
        }

        //保存购物车
        Redis::setex($this->auto_code, 360000, json_encode($this->bill_array));

        if (!is_null($c)) {
            return ['code' => 200, 'message' => 'ok', 'data' => $c];
        } else {
            return ['code' => 200, 'message' => 'ok', 'data' => $data];
        }
    }

    /**
     * 购物车计算
     * @param $bill_array
     * @param $pcustID
     * @param $shop_id
     */
    public static function checkout($bill_array, $pcustID, $shop_id)
    {

        $return_array = array(
            'bill_totalMoney' => 0,
            'bill_totalPaid' => 0,
            'bill_payable' => 0,
            'bill_total_amount' => 0,
            'bill_coupon_money' => 0,
            'bill_bag_money' => 0,
            'bill_totalPoints' => 0,
            'bill_pointsPrice' => 0,
            'goods' => []
        );

        if (!isset($bill_array['goods']) || empty($bill_array['goods'])) {
            return ['code' => 404, 'message' => '您还没有购买商品，请先添加商品'];
        }

        //商品数组，用来统计商品购买数量
        $c_goods_array = array();

        //普通订单商品
        if (isset($bill_array['goods']['general'])) {

            foreach($bill_array['goods']['general'] as $key=>$goods){

                if (isset($goods['is_buy']) && $goods['is_buy'] == 0) {
                    continue;
                }

                if ( isset($c_goods_array[$goods['postID']]) ) {
                    $goods_amount = $c_goods_array[$goods['postID']] + $goods['goods_amount'];
                } else {
                    $goods_amount = $goods['goods_amount'];
                }

                $goods_array = GoodsSale::getCache($goods['postID'], $shop_id);
                if (!$goods_array) {
                    unset($bill_array['goods']['general'][$goods['postID']]);
                    continue;
                }

                $return_array = self::totalBillGoodsData($return_array, $goods);

                $return_array['goods']['general'][$key] = $goods;
            }
        }

        //购物袋
        if (isset($bill_array['goods']['shopping_bag'])) {

            foreach($bill_array['goods']['shopping_bag'] as $key=>$goods){

                $return_array['bill_bag_money'] += round($goods['price'] * $goods['goods_amount'], 2);

                $return_array['goods']['shopping_bag'][$key] = $goods;
            }
        }

        //优惠券具体优惠方式：cardType:1、代金券 2、折扣券
        if (isset($bill_array['use_coupon'])) {

            if ($bill_array['use_coupon']['cardType'] == 1) {
                $return_array['bill_coupon_money'] += $bill_array['use_coupon']['amount'];
            }

            if ($bill_array['use_coupon']['cardType'] == 2 && !empty($bill_array['use_coupon']['discount'])) {
                $return_array['bill_coupon_money'] += $bill_array['use_coupon']['amount'];
            }
        }

        //计算订单应付金额
        $return_array['bill_totalMoney'] += $return_array['bill_bag_money'];
        $return_array['bill_totalPaid'] += $return_array['bill_bag_money'];
        $return_array = self::calculationBillPayable($return_array, 0);

        $bill_array['master']['bill_totalMoney']   = $return_array['bill_totalMoney'];
        $bill_array['master']['bill_totalPaid']    = $return_array['bill_totalPaid'];
        $bill_array['master']['bill_total_amount'] = $return_array['bill_total_amount'];
        $bill_array['master']['bill_coupon_money'] = $return_array['bill_coupon_money'];
        $bill_array['master']['bill_payable']      = $return_array['bill_payable'];
        $bill_array['master']['bill_pointsPrice']  = $return_array['bill_pointsPrice'];

        $return_data = [$bill_array, $return_array];

        return ['code' => 200, 'message' => 'ok', 'data' => $return_data];

    }

    /**
     * 统计订单商品数据
     * @param $total_array
     * @param $goods
     * @return mixed
     */
    public static function totalBillGoodsData($total_array, $goods, $amount_flg=1)
    {

        $return_array = $total_array;
        $return_array['bill_totalMoney']   += round($goods['salePrice'] * $goods['goods_amount'], 2);
        $return_array['bill_totalPaid']    += round($goods['price'] * $goods['goods_amount'], 2);
        $return_array['bill_totalPoints']  += $goods['salePoints'] * $goods['goods_amount'];
        $return_array['bill_pointsPrice']  += $goods['addPoints'] * $goods['goods_amount'];
        if ($amount_flg == 1) {
            $return_array['bill_total_amount'] += $goods['goods_amount'];
        }
        return $return_array;

    }

    /**
     * 订单应付款
     * @param $total_array
     * @param $deliver_fee
     * @return mixed
     */
    public static function calculationBillPayable( $total_array, $deliver_fee ) {

        $return_array = $total_array;

        $payable = $total_array['bill_totalPaid'] - $total_array['bill_coupon_money'];
        if ( $payable <= 0 ) {
            $payable = 0;
        }

        $payable += $deliver_fee;

        $return_array['bill_payable'] = round($payable, 2);

        return $return_array;

    }

    /**
     * 格式化字符串类型的请求以及返回参数
     * @param $val
     * @param string $default
     * @return string
     */
    public static function toString($val, $default = '')
    {
        if (! isset($val)) {
            return $default;
        } else {
            if (is_null($val) || $val == '')
                return $default;
            return strval($val);
        }
    }

    /**
     * 格式化int类型的请求以及返回参数
     * @param $val
     * @param int $default
     * @return int
     */
    public static function toInt($val, $default = 0)
    {
        if (! isset($val)) {
            return $default;
        } else {
            return intval($val);
        }
    }

    /**
     * 用作测试，获取redis值
     */
    public function getredis( Request $request )
    {
        $bill_data = [
            'timeStamp' => Carbon::now(),
            'createTime' => Carbon::now(),
            'extend_6' => null
        ];

        error_log(print_r($bill_data,true));
    }
}